package com.water.app.Controller.chat;

import cn.hutool.json.JSONUtil;
import com.water.app.*;
import com.water.app.interfaces.account.userService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api/chat")
public class ChatController {

    private static final Logger log = LoggerFactory.getLogger(ChatAiController.class);
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private userService userService;

    @Resource
    private RedisUtils redisUtils;
    //查询历史聊过天的人
    @GetMapping("/historyChatUser")
    public Result getHistoryChatUser(){
        log.info("正在查询历史聊天的人");
        Integer userId = Constant.THREAD_LOCAL.get();
        String pattern1=Constant.CHAT_PRIVATE+"user1:"+userId+":user2:*";
        String pattern2=Constant.CHAT_PRIVATE+"user1:*:user2:"+userId;
        List<String> keyList1 = new ArrayList<>(redisUtils.scanKeysByPattern(pattern1));
        List<String> keyList2=new ArrayList<>(redisUtils.scanKeysByPattern(pattern2));

        //保存用户id的集合
        List<Integer> chatUserIds = new ArrayList<>();

        //正则表达式匹配出不是当前用户的用户id
        String regex = Constant.CHAT_PRIVATE + "user1:(\\d+):user2:(\\d+)";
        Pattern pattern = Pattern.compile(regex);


        //根据key找聊天对象的list队列
        for (String key1 : keyList1) {
            List<String> range = stringRedisTemplate.opsForList().range(key1, 0, -1);
            Matcher matcher1 = pattern.matcher(key1);
            if (matcher1.matches()) {
                Integer user1 = Integer.parseInt(matcher1.group(1));
                Integer user2 = Integer.parseInt(matcher1.group(2));
                // 聊天对象 ID 是“不是当前用户的那个 ID”
                Integer chatUserId = (user1.equals(userId)) ? user2 : user1;
                chatUserIds.add(chatUserId);
            }
        }

        for (String key2 : keyList2) {
            Matcher matcher2 = pattern.matcher(key2);
            if (matcher2.matches()) {
                Integer user1 = Integer.parseInt(matcher2.group(1));
                Integer user2 = Integer.parseInt(matcher2.group(2));
                // 聊天对象 ID 是“不是当前用户的那个 ID”
                Integer chatUserId = (user1.equals(userId)) ? user2 : user1;
                chatUserIds.add(chatUserId);
            }
        }

        if (chatUserIds.isEmpty()){
            return Result.success(2,"当前没有消息哦",null);
        }
        List<User> userList = userService.selectUserListByUserId(chatUserIds);
        for (int i=0;i<keyList1.size();i++) {
            //所有消息的未封装的消息体
            List<String> range = stringRedisTemplate.opsForList().range(keyList1.get(i), 0, -1);
            //如果是temp就是刚创建聊天窗口，此时没有消息，没必要封装
            if(range.contains("temp")&&range.size()==1){
                break;
            }

            //查看所有未读消息
            long count = range.stream().filter(e -> {
                PrivateChatMsg bean = JSONUtil.toBean(e, PrivateChatMsg.class);
                //如果是别人的消息没有看，就计数，自己的不计数
                return bean.getIsLook() == 0&&bean.getSender()!=userId;
            }).count();
            List<String> range1 = stringRedisTemplate.opsForList().range(keyList1.get(i), 0, -1);
            Matcher matcher1 = pattern.matcher(keyList1.get(i));
            Integer chatUserId=null;
            if (matcher1.matches()) {
                Integer user1 = Integer.parseInt(matcher1.group(1));
                Integer user2 = Integer.parseInt(matcher1.group(2));
                // 聊天对象 ID 是“不是当前用户的那个 ID”
                chatUserId = (user1.equals(userId)) ? user2 : user1;
            }
            User user = userService.selectUser(chatUserId);
            //把相对应用户的messageNumber设置为count，这里是防止user为空导致空指针异常，断点调试的
            if(userList.indexOf(user)==-1){
                continue;
            }
            List<String> message = stringRedisTemplate.opsForList().range(keyList1.get(i), 0, 0);
            userList.get(userList.indexOf(user)).setMessageNumber((int)count);
            userList.get(userList.indexOf(user)).setLastMessage(
                    JSONUtil.toBean(message.get(0),PrivateChatMsg.class).getMsg()
            );
        }

        for (int i=0;i<keyList2.size();i++) {
            //所有消息的未封装的消息体
            List<String> range = stringRedisTemplate.opsForList().range(keyList2.get(i), 0, -1);
            if(range.contains("temp")&&range.size()==1){
                break;
            }
            //查看所有未读消息
            long count = range.stream().filter(e -> {
                PrivateChatMsg bean = JSONUtil.toBean(e, PrivateChatMsg.class);
                boolean isTrue=bean.getIsLook() == 0&&bean.getSender()!=userId;
                //如果是别人的消息没有看，就计数，自己的不计数
                return bean.getIsLook() == 0&&bean.getSender()!=userId;
            }).count();
            List<String> range1 = stringRedisTemplate.opsForList().range(keyList2.get(i), 0, -1);
            Matcher matcher1 = pattern.matcher(keyList2.get(i));
            Integer chatUserId=null;
            if (matcher1.matches()) {
                Integer user1 = Integer.parseInt(matcher1.group(1));
                Integer user2 = Integer.parseInt(matcher1.group(2));
                // 聊天对象 ID 是“不是当前用户的那个 ID”
                chatUserId = (user1.equals(userId)) ? user2 : user1;
            }
            User user = userService.selectUser(chatUserId);
            //把相对应用户的messageNumber设置为count，这里是防止user为空导致空指针异常，断点调试的
            if(userList.indexOf(user)==-1){
                continue;
            }
            List<String> message = stringRedisTemplate.opsForList().range(keyList2.get(i), 0, 0);
            userList.get(userList.indexOf(user)).setMessageNumber((int)count);
            userList.get(userList.indexOf(user)).setLastMessage(
                    JSONUtil.toBean(message.get(0),PrivateChatMsg.class).getMsg()
            );
        }

        return Result.success(1, "查询用户列表成功", userList);
    }
    //查询某个人的历史聊天记录
    @GetMapping("/historyMsgList/{userId}")
    public Result getHistoryMsgList(@PathVariable("userId")Integer id){
        if (id==null||id<0){
            return Result.error("传参错误");
        }
        Integer userId = Constant.THREAD_LOCAL.get();
        log.info("用户{}正在查询和用户{}的聊天记录",userId,id);
        int max = Math.max(id, userId);
        int min = Math.min(id, userId);
        String key=Constant.CHAT_PRIVATE+"user1:"+min+":user2:"+max;
        List<String> msgList = stringRedisTemplate.opsForList().range(key, 0, -1);
        List<PrivateChatMsg> list=new ArrayList<>();
        try {
            for(String msgStr:msgList){
                PrivateChatMsg bean = JSONUtil.toBean(msgStr, PrivateChatMsg.class);
                list.add(bean);
            }
        } catch (Exception e) {
            return Result.success(2,"聊天记录为空",null);
        }
        log.info("消息封装完毕:{}",list);
        List<PrivateChatMsg> list1 = list.stream().map(e -> {
            if(e.getSender()==id) {
                e.setIsLook(1);
            }
            return e;
        }).toList();
        if(list!=null&&!list.isEmpty()){
        for(int i=list1.size()-1;i>=0;i--){
            PrivateChatMsg p = list1.get(i);
            String jsonStr = JSONUtil.toJsonStr(p);
            stringRedisTemplate.opsForList().set(key,i,jsonStr);
        }
        }
        if(list.isEmpty()){
            return Result.success(1,"暂无聊天记录",null);
        }else {
            return Result.success(1, "查询历史聊天记录成功", list);
        }
    }

    @PostMapping("/addUserChatIfAbsent")
    public Result addUserChatIfAbsent(@RequestBody shop shop){
        int userId = shop.getUserId();
        Integer id = Constant.THREAD_LOCAL.get();
        log.info("用户{}正在和用户{}建立聊天",id,userId);
        User user= userService.selectUser(userId);
        int max = Math.max(id, userId);
        int min = Math.min(id, userId);
        String key=Constant.CHAT_PRIVATE+"user1:"+min+":user2:"+max;
        List<String> temp = stringRedisTemplate.opsForList().range(key, 0, 0);
        if(temp!=null&&temp.contains("temp")){
            log.info("当前会话已经存在");
        }else {
            log.info("正在创建新的会话");
            stringRedisTemplate.opsForList().leftPush(key,"temp");
        }
        log.info("创建聊天列表成功");
        return Result.success(1,"创建聊天列表成功",user);
    }

}
